//eslint-disable-next-line
import React, { useEffect, useState } from 'react';

const useSocket = (path, onClose) => {
    const [socket, setSocket] = useState();
    const [val, setVal] = useState();
    useEffect(() => {
        if (!window.WebSocket) {
            return;
        }

        console.log('socket init');

        const ws = new WebSocket(window.TDT_CONFIG.WEBSOCKET_URL + path);
        ws.onopen = function () {
            console.log('success');
        };
        ws.onclose = function () {
            if (onClose) {
                onClose();
            }
            console.log('close');
        };
        ws.onerror = function () {
            console.log('error');
        };
        ws.onmessage = function (e) {
            // console.log('接收到消息: ' + e.data);
            setVal(JSON.parse(e.data));
        };
        // ws.send("发送数据");

        setSocket(ws);
    }, [path]);
    useEffect(() => {
        return () => {
            try {
                if (socket) {
                    socket.close();
                }
            } catch (e) {
                console.log(e);
            }
        };
    }, [socket]);

    return [val, socket];
};

export default useSocket;
